package org.example.likou150.hash;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

// https://leetcode.cn/problems/longest-consecutive-sequence/?envType=study-plan-v2&envId=top-interview-150
public class LongestConsecutive {
//    输入：nums = [100,4,200,1,3,2]
//    输出：4
//    解释：最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4

    public static void main(String[] args) {
        LongestConsecutive longestConsecutive=new LongestConsecutive();
        ;
        System.out.println(longestConsecutive.longestConsecutive(new int[]{100,4,200,1,3,2}));
    }

    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        int maxLength=0;
        for (int num : set) {
            if(!set.contains(num-1)){
                int temp=num;
                int count=0;
                while (set.contains(temp+1)){
                    temp++;
                    count++;
                }
                maxLength=Math.max(maxLength,  count+1);
            }
        }
        return maxLength;
    }

//    public int longestConsecutive(int[] nums) {
//        Set<Integer> set = new HashSet<>();
//        for (int num : nums) {
//            set.add(num);
//        }
//        int maxLength=0;
//        for (int i = 0; i < nums.length; i++) {
//            int temp=nums[i];
//            int length=0;
//            while(set.contains(++temp)){
//                length++;
//            }
//            maxLength = Math.max(maxLength, length+1);
//        }
//        return maxLength;
//    }
}
